package com.zc.framework.shiro.dao;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by zc on 2016/8/19.
 */
public class RedisShiroCacheManager implements CacheManager {

    private static final Logger logger = LogManager.getLogger(RedisShiroCacheManager.class);

    private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<>();

    private RedisShiroManager redisShiroManager;

    private String keyPrefix = "shiro_redis_cache:";


    @Override
    public <K, V> Cache<K, V> getCache(String name) {
        logger.info("cache name: {} RedisCache instance", name);

        Cache cache = caches.get(name);

        if(cache == null ){
            redisShiroManager.init();
            cache = (Cache) new RedisShiroCache<K, V>(redisShiroManager, keyPrefix);

            // add it to the cache collection
            caches.put(name, cache);
        }
        return cache;
    }

    public RedisShiroManager getRedisShiroManager() {
        return redisShiroManager;
    }

    public void setRedisShiroManager(RedisShiroManager redisShiroManager) {
        this.redisShiroManager = redisShiroManager;
    }

    public String getKeyPrefix() {
        return keyPrefix;
    }

    public void setKeyPrefix(String keyPrefix) {
        this.keyPrefix = keyPrefix;
    }
}
